package com.xyy.dfapi.utils;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

public class CacheUtils {

    private static final Cache<String, Object> cache = CacheBuilder.newBuilder()
            //设置缓存初始大小，应该合理设置，后续会扩容
            .initialCapacity(10)
            //最大值
            .maximumSize(200)
            //并发数设置
            .concurrencyLevel(5)
            //缓存过期时间，写入后5秒钟过期
            //.expireAfterWrite(24*5, TimeUnit.HOURS)
            .recordStats()
            .build();

    private CacheUtils() {
    }

    public static Object get(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        return cache.getIfPresent(key);
    }


    public static void set(String key, Integer value) {
        if (StringUtils.isBlank(key) || Objects.isNull(value) || value < 0) {
            return;
        }
        cache.put(key, value);
    }

    public static void set(String key, String value) {
        if (StringUtils.isBlank(key) || Objects.isNull(value)) {
            return;
        }
        cache.put(key, value);
    }

    public static void remove(String key) {
        if (StringUtils.isBlank(key)) {
            return;
        }
        cache.invalidate(key);
    }


}
